<?php

namespace app\api\controller;

use app\facade\Redis;
use app\facade\Mns;
use app\models\{Quotes, Annou, Banner, Config, Helps, Order, Orderlog, Kefu};
use think\facade\Env;
use think\Validate;
use think\Facade\Config as Configs;
use think\Db;
use oss\Oss;
use think\facade\Debug;

class Other extends Base
{
    private $url = 'https://api-aws.huobi.pro/';

    public function aboutus()
    {
        $result = [
            'aboutus' => '',
            'version' => '1.0.0',
            'android' => '',
            'ios' => ''
        ];
        $result['aboutus'] = (new Config())->where('key_value', 'aboutus')->value('value');
        $result['version'] = (new Config())->where('key_value', 'version')->value('value');
        $result['android'] = (new Config())->where('key_value', 'android')->value('value');
        $result['whitepaper'] = (new Config())->where('key_value', 'whitepaper')->value('value');
        $result['ios'] = (new Config())->where('key_value', 'ios')->value('value');
        $this->result($result, 0, '获取成功');
    }
    //发送短信
    public function sendCode()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'type' => 'require|in:1,2',
            'account' => 'require',
        ], [
            'type.require' => '账号类型不能为空',
            'type.in' => '账号类型错误',
            'account.require' => '账号不能为空',
            'code.require' => '验证码必须填写',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        switch ($data['type']) {
            case '1':
                if (empty($data['country'])) {
                    $this->result([], 1, '国家区号不能为空');
                }
                $CheckCode = (new Mns)->send($data['type'], $data['account'], $data['country']);
                break;
            case '2':
                $CheckCode = (new Mns)->send($data['type'], $data['account']);
                break;
            default:
                $this->result([], 1, '类型错误');
                break;
        }
        if (!$CheckCode) {
            $this->result([], 1, $CheckCode['msg']);
        }
        $this->result([], 0, $CheckCode['msg']);
    }

    public function banner()
    {
        $type = $this->request->get('type/d', 0);
        $list = (new Banner())->where('type', $type)->field('created', true)->select();
        $this->result($list, 0, '获取成功');
    }

    public function Kefu()
    {
        $list = (new Kefu())->field('created', true)->select();
        $this->result($list, 0, '获取成功');
    }

    public function helps()
    {
        $list = (new Helps())->field('created', true)->select();
        $this->result($list, 0, '获取成功');
    }

    public function Annou()
    {
        $list = (new Annou())->field('id,title,infos,times')->order('times desc')->limit(20)->select();
        $this->result($list, 0, '获取成功');
    }

    public function oss()
    {
        $result = [];
        try {
            $result = (new Oss())->getCredentials();
            $result['regionId'] = Env::get('aliyun.regionId');
            $result['bucket'] = Env::get('aliyun.bucket');
            $result['endpoint'] = Env::get('aliyun.endpoint');
        } catch (\Throwable $th) {
            $result = [];
        }
        $this->result($result, 0, '获取成功');
    }

    public function Quotes()
    {
        $list = (new Quotes())->where('ishow', 1)->select();
        $data = [];
        $rdslist = Redis::get('quotekline');
        if ($rdslist) {
            $data = unserialize($rdslist);
        }
        $this->result($data, 0, '获取成功');
    }

    public function Quotesone()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new Quotes())->where('id', $id)->where('ishow', 1)->find();
        $data = [];
        $coin = Configs::get('config.coins.' . $lists['coin']);
        $mart = Configs::get('config.martcoins.' . $lists['mart']);
        $data[$id] = [
            'id' => $id,
            'istrans' => $lists['istrans'],
            'coins' => $coin,
            'mart' => $mart,
            'high' => 0,
            'low' => 0,
            'vol' => 0, //成交量
            'close' => 0, //最新价
            'open' => 0, //开盘价
            'quto' => 0, //开盘价
            'pubdate' => $lists['pubdate'],
            'pubtotal' => $lists['pubtotal'],
            'currtotal' => $lists['currtotal'],
            'crowdprice' => $lists['crowdprice'],
            'whitepaper' => $lists['whitepaper'],
            'website' => $lists['website'],
            'blockqurey' => $lists['blockqurey'],
            'info' => $lists['info']
        ];
        if (empty($lists)) {
            $this->result($data, 0, '获取成功');
        }
        if ($lists['coin'] == 1) {
            //通过订单记录获取24小时行情
            $time = date('Y-m-d H:i:s', (time() - 86400));
            $coinorder = (new Order())
                ->order('clostime desc')
                ->field('transnum,transprice')
                ->where('clostime', '>=', $time)
                ->where(['coin' => $lists['coin'], 'mart' => $lists['mart'], 'status' => 2])
                ->select();
            $ordercount = count($coinorder);
            if (!empty($coinorder) && $ordercount > 0) {
                $data[$lists['id']]['open'] =  $coinorder[($ordercount - 1)]['transprice'];
                $data[$lists['id']]['close'] =  $coinorder[0]['transprice'];
                if ($data[$lists['id']]['open'] > 0) {
                    $data[$lists['id']]['quto'] = ($data[$lists['id']]['close'] - $data[$lists['id']]['open']) * 100 / $data[$lists['id']]['open']; //开盘价
                }
                $volnum = 0;
                $maxprice = 0;
                $minprice = 0;
                for ($i = 0; $i < $ordercount; $i++) {
                    $volnum += $coinorder[$i]['transnum'];
                    if ($coinorder[$i]['transprice'] > $maxprice) {
                        $maxprice = $coinorder[$i]['transprice'];
                    }
                    if ($coinorder[$i]['transprice'] < $minprice || $minprice == 0) {
                        $minprice = $coinorder[$i]['transprice'];
                    }
                }
                $data[$lists['id']]['high'] =  $maxprice;
                $data[$lists['id']]['low'] =  $minprice;
                $data[$lists['id']]['vol'] =  $volnum;
            }
        } else {
            $url = $this->url . "market/history/kline?symbol=" . strtolower($coin . $mart) . '&period=1day&size=1';
            $result = api_curl($url);
            $client = json_decode($result, true);
            if (!empty($client['status']) && $client['status'] == 'ok') {
                $data[$lists['id']] = [
                    'id' => $lists['id'],
                    'logo' => $lists['logos'],
                    'istrans' => $lists['istrans'],
                    'coins' => $coin,
                    'mart' => $mart,
                    'high' => $client['data'][0]['high'],
                    'low' => $client['data'][0]['low'],
                    'vol' => $client['data'][0]['vol'], //成交量
                    'close' => $client['data'][0]['close'], //最新价
                    'open' => $client['data'][0]['open'], //开盘价
                    'quto' => floor(($client['data'][0]['close'] - $client['data'][0]['open']) * 1000000 / $client['data'][0]['open']) / 10000, //开盘价
                    'pubdate' => $lists['pubdate'],
                    'pubtotal' => $lists['pubtotal'],
                    'currtotal' => $lists['currtotal'],
                    'crowdprice' => $lists['crowdprice'],
                    'whitepaper' => $lists['whitepaper'],
                    'website' => $lists['website'],
                    'blockqurey' => $lists['blockqurey'],
                    'info' => $lists['info']
                ];
            }
        }
        $data = $data[$lists['id']];
        $this->result($data, 0, '获取成功');
    }

    public function QuotesIndex()
    {
        $id = $this->request->get('id/d', 0);
        $type = $this->request->get('type/d', 1);
        $size = 150; //数据长度
        if ($id == 0 || $type == 0) {
            $this->result([], 1, '参数错误');
        }
        $lists = (new Quotes())->where('id', $id)->find();
        if (empty($lists)) {
            $this->result([], 0, '获取成功');
        }
        $data = [];
        $coin = Configs::get('config.coins.' . $lists['coin']);
        $mart = Configs::get('config.martcoins.' . $lists['mart']);
        if ($lists['coin'] != 1) {
            if ($type == 1) {
                $period = '1min';
            } elseif ($type == 5) {
                $period = '5min';
            } elseif ($type == 15) {
                $period = '15min';
            } elseif ($type == 30) {
                $period = '30min';
            } elseif ($type == 60) {
                $period = '60min';
            } elseif ($type == 1440) {
                $period = '1day';
            } else {
                $period = '';
            }
            $url = $this->url . "market/history/kline?symbol="
                . strtolower($coin . $mart) . '&size=' . $size . '&period=' . $period;
            $result = api_curl($url);
            $client = json_decode($result, true);
            if (!empty($client['status']) && $client['status'] == 'ok') {
                $data = $client['data'];
            }
            foreach ($data as &$datas) {
                $datas['id'] = date('Y-m-d H:i:s', $datas['id']);
                unset($datas['amount']);
                unset($datas['count']);
            }
        } else {
            $data = [];
            $rdscoinmart = 'coinquote' . $lists['id'] . 'type_' . $type;
            $valuerds = Redis::get($rdscoinmart); //获取值
            if ($valuerds) {
                $data = unserialize($valuerds);
            }
        }
        $this->result($data, 0, '获取成功');
    }

    public function jiaoyiLog()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'id' => 'require|gt:0',
        ], [
            'id.require' => 'ID不能为空',
            'id.gt' => 'ID必须大于0',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $list = [];
        $quotes = (new Quotes())->where('id', $data['id'])->find();
        if (empty($quotes)) {
            $this->result($list, 0, '查询完成');
        }
        $coin = Configs::get('config.coins.' . $quotes['coin']);
        $mart = Configs::get('config.coins.' . $quotes['mart']);
        if ($quotes['coin'] == 1) {
            $data1 = [];
            $list = (new Orderlog())->order('id desc')->field('price,num,type,created')
                ->where(['coins' => $quotes['coin'], 'mart' => $quotes['mart']])->limit(20)->select();
            foreach ($list as $lists) {
                if ($lists['type'] == 2) {
                    $lists['num'] = round($lists['num'] / $lists['price'], 6);
                } else {
                    $lists['num'] = round($lists['num'], 6);
                }
            }
        } else {
            $url = $this->url . "market/history/trade?size=20&symbol=" . strtolower($coin . $mart);
            $result = api_curl($url);
            $client = json_decode($result, true);
            if (!empty($client['status']) && $client['status'] == 'ok') {
                $lista = $client['data'];
                foreach ($lista as $lists) {
                    $lists = $lists['data'];
                    for ($i = 0; $i < count($lists); $i++) {
                        $list[] = [
                            'price' => $lists[$i]['price'],
                            'num' => $lists[$i]['amount'],
                            'type' => $lists[$i]['direction'] == 'sell' ? 2 : 1,
                            'created' => date('H:i:s', (int)($lists[$i]['ts'] / 1000))
                        ];
                    }
                }
            }
        }
        $this->result($list, 0, '查询完成');
    }


    public function Orderlog()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'id' => 'require|gt:0',
        ], [
            'id.require' => 'ID不能为空',
            'id.gt' => 'ID必须大于0',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $list = [];
        $data1 = [];
        $data2 = [];
        $quotes = (new Quotes())->where('id', $data['id'])->find();
        if (empty($quotes)) {
            $this->result($list, 0, '查询完成');
        }
        $coin = Configs::get('config.coins.' . $quotes['coin']);
        $mart = Configs::get('config.coins.' . $quotes['mart']);
        if ($quotes['coin'] == 1) {
            $data1 = [];
            $ordertype = (new Order())->order('commprice desc')->field('commprice,commnum,type,transnum')
                ->where(['coin' => $quotes['coin'], 'mart' => $quotes['mart'], 'type' => 1, 'status' => 1, 'prmoney' => 1])
                ->order('id desc')->select();
            $wtj = 0;
            foreach ($ordertype as $k => $v) {
                if ($wtj <= 0) {
                    $wtj = $v['commprice'];
                } elseif ($wtj < $v['commprice']) {
                    $wtj = $v['commprice'];
                }
                if (empty($data1[$v['commprice']])) {
                    $data1[$v['commprice']]['commprice'] = $v['commprice'];
                    $data1[$v['commprice']]['type'] = $v['type'];
                    $data1[$v['commprice']]['commnum'] = $v['commnum'] - $v['transnum'];
                } else {
                    $data1[$v['commprice']]['commnum'] += $v['commnum'] - $v['transnum'];
                }
            }
            $data1 = array_values($data1);
            $data1 = array_slice($data1, 0, 20);
            $ordertype2 = (new Order())->order('commprice asc')->field('commprice,commnum,type,transnum')
                ->where(['coin' => $quotes['coin'], 'mart' => $quotes['mart'], 'type' => 2, 'status' => 1, 'prmoney' => 1])
                ->where('commprice', '>=', $wtj)->order('id desc')->select();
            $data2 = [];
            foreach ($ordertype2 as $k => $v) {
                if (empty($data2[$v['commprice']])) {
                    $data2[$v['commprice']]['commprice'] = $v['commprice'];
                    $data2[$v['commprice']]['type'] = $v['type'];
                    $data2[$v['commprice']]['commnum'] = $v['commnum'] - $v['transnum'];
                } else {
                    $data2[$v['commprice']]['commnum'] += $v['commnum'] - $v['transnum'];
                }
            }
            $data2 = array_values($data2);
            $data2 = array_slice($data2, 0, 20);
            array_multisort(array_column($data2, 'commprice'), SORT_DESC, $data2);
        } else {
            $url = $this->url . "market/history/trade?size=50&symbol=" . strtolower($coin . $mart);
            $result = api_curl($url);
            $client = json_decode($result, true);
            if (!empty($client['status']) && $client['status'] == 'ok') {
                $lists = $client['data'];
                foreach ($lists as $list) {
                    $list = $list['data'];
                    for ($i = 0; $i < count($list); $i++) {
                        if (count($data1) < 20 && $list[$i]['direction'] == 'buy') {
                            $data1[] = [
                                'commprice' => $list[$i]['price'],
                                'commnum' => $list[$i]['amount'],
                                'type' => 1
                            ];
                        }
                        if (count($data2) < 20 && $list[$i]['direction'] == 'sell') {
                            $data2[] = [
                                'commprice' => $list[$i]['price'],
                                'commnum' => $list[$i]['amount'],
                                'type' => 2
                            ];
                        }
                    }
                }
            }
        }
        $list = array_merge_recursive($data1, $data2);
        $this->result($list, 0, '查询完成');
    }
}
